package org.dubnation.base.commons;

import org.apache.commons.io.FilenameUtils;
import org.dubnation.base.util.AjaxResult;
import org.dubnation.base.util.fastdfs.FastdfsUtil;
import org.dubnation.org.domain.Shop;
import org.dubnation.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {

    @Value("${fastdfs.storage}")
    private String prefixUrl;

    @Autowired
    private IShopService shopService;

    /**
     * 前端文件上传到分布式文件服务器
     * @param logo
     * @return
     */
    @PostMapping("/upload")  //传送文件只能用post请求,get请求数据有大小限制
    public AjaxResult upload(@RequestParam("file") MultipartFile logo) {
        String filename = logo.getOriginalFilename();  //获取真实文件名
        String suffixName = FilenameUtils.getExtension(filename); //获取文件的后缀
        String fileUrl = null;
        try {
            //获取文件存储在分布式文件系统中的地址
            fileUrl = FastdfsUtil.upload(logo.getBytes(), suffixName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.me().setMessage("文件上传成功").setData(prefixUrl + fileUrl);
    }

    /**
     * 删除分布式文件服务器中的图片
     * @param path
     * @return
     */
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("path") String path) {
        //将logo从文件服务器中删除
        FastdfsUtil.delete(path);
        //将logo地址从数据库中删除
        Shop shop = shopService.queryByLogo(path);
        shop.setLogo("");
        shopService.update(shop);
        return AjaxResult.me();
    }
}
